<?php
/**
 * 修复测试数据 - 为当前测试用户添加会员数据
 */

require_once __DIR__ . '/vendor/autoload.php';
require_once __DIR__ . '/support/bootstrap.php';

use think\facade\Db;

echo "🔧 修复测试数据...\n";

try {
    // 获取当前测试用户信息（根据邮箱模式匹配）
    echo "📋 获取当前测试用户...\n";
    $testUser = Db::name('gf_et_users')
        ->where('email', 'like', 'testapi_%@example.com')
        ->order('id', 'desc')
        ->find();
    
    if (!$testUser) {
        echo "❌ 未找到测试用户\n";
        exit(1);
    }
    
    echo "✅ 找到测试用户: ID={$testUser['id']}, Email={$testUser['email']}\n";
    
    // 删除现有的会员记录（如果有）
    echo "🗑️  清理现有会员记录...\n";
    Db::name('gf_user_memberships')
        ->where('user_id', $testUser['id'])
        ->delete();
    
    // 创建新的会员记录
    echo "📋 创建新的会员记录...\n";
    $membershipData = [
        'user_id' => $testUser['id'],
        'plan_type' => 'basic',
        'status' => 'active',
        'start_date' => date('Y-m-d', strtotime('-1 day')),
        'end_date' => date('Y-m-d', strtotime('+1 year')),
        'auto_renew' => 1,
        'created_at' => date('Y-m-d H:i:s'),
        'updated_at' => date('Y-m-d H:i:s')
    ];
    
    Db::name('gf_user_memberships')->insert($membershipData);
    
    echo "✅ 会员记录已创建\n";
    
    // 验证会员记录
    echo "🔍 验证会员记录...\n";
    $membership = Db::name('gf_user_memberships')
        ->where('user_id', $testUser['id'])
        ->find();
    
    if ($membership) {
        echo "✅ 会员记录验证成功\n";
        echo "   会员ID: {$membership['id']}\n";
        echo "   用户ID: {$membership['user_id']}\n";
        echo "   套餐类型: {$membership['plan_type']}\n";
        echo "   状态: {$membership['status']}\n";
        echo "   开始日期: {$membership['start_date']}\n";
        echo "   结束日期: {$membership['end_date']}\n";
    } else {
        echo "❌ 会员记录验证失败\n";
        exit(1);
    }
    
} catch (\Exception $e) {
    echo "❌ 修复失败: " . $e->getMessage() . "\n";
    exit(1);
}

echo "🎉 测试数据修复完成！\n";